import { hasClass } from "element-plus/es/utils";

class HashTable<T> {
  //创建一个数组，用于存放链地址中的链（数组）
  private storage: [string, T][][] = [];
  //定义数组的长度
  private length: number = 7;
  //记录已经存放元素的个数
  private count: number = 0;

  //hash内部自己实现的生成index方法
  hashFunc(str: string, max: number = this.length, BaseNum = 27) {
    //计算hashCode cats==>60337(27为底的时候)
    let hashCode = 0;
    const length = str.length;
    for (let i = 0; i < length; i++) {
      hashCode = BaseNum * hashCode + str.charCodeAt(i);
    }
    const index = hashCode % max;
    return index;
  }

  //添加或者修改
  put(key: string, value: T) {
    //生成索引
    const index = this.hashFunc(key, this.length);

    //找到对应索引的bucket桶存储
    let bucket = this.storage[index];

    //判断bucket是否有值
    if (!bucket) {
      //未创建情况
      bucket = [];
      this.storage[index] = bucket;
    }
    let isUpdate = false;
    for (let i = 0; i < bucket.length; i++) {
      const tuple = bucket[i];
      const tupleKey = tuple[0];
      if (tupleKey === key) {
        //修改情况
        tuple[1] = value;
        isUpdate = true;
      } else {
        isUpdate = false;
      }
    }

    //新增情况
    if (!isUpdate) {
      bucket.push([key, value]);
      this.count++;
    }
  }

  //获取某个值
  get(key: string): T | undefined {
    const index = this.hashFunc(key, this.length);
    //找到对应索引的bucket桶存储
    let bucket = this.storage[index];
    if (!bucket) {
      return undefined;
    }
    for (let i = 0; i < bucket.length; i++) {
      const tuple = bucket[i];
      const tupleKey = tuple[0];
      if (tupleKey === key) {
        return tuple[1];
      }
    }

    return undefined;
  }

  //获取所有的值
  getAll() {
    return this.storage;
  }

  //删除操作
  delete(key: string): T | undefined {
    const index = this.hashFunc(key, this.length);
    //找到对应索引的bucket桶存储
    let bucket = this.storage[index];
    if (!bucket) {
      return undefined;
    }
    for (let i = 0; i < bucket.length; i++) {
      const tuple = bucket[i];
      const tupleKey = tuple[0];
      if (tupleKey === key) {
        bucket.splice(i, 1);
        this.count--;
        return tuple[1];
      }
    }

    return undefined;
  }
}

const hashTable = new HashTable();
hashTable.put("aaa", 1000);
hashTable.put("bbb", 2000);
hashTable.put("ccc", 3000);
hashTable.put("ddd", 4000);
hashTable.put("abc", 5000);
console.log(hashTable.get("ddd"));

console.log(hashTable.delete("ccc"));

console.log(hashTable.getAll());

export {};
